package com.unicom.office.func;

import com.unicom.office.runtime.OfficeRuntime;
import com.unicom.office.type.TypeItem;
import com.unicom.office.templateproc.TemplateProc;
import com.unicom.office.unit.OfficeUnit;

import java.util.ArrayList;
import java.util.List;

public class ProcNode extends FuncCommon {
    private TemplateProc templateProc;
    protected List<Object> params;

    public ProcNode(TemplateProc templateProc) {
        this.templateProc = templateProc;
        this.params = new ArrayList<Object>();
    }

    public void run(OfficeUnit unit, OfficeRuntime officeRuntime){
        List<Object> list = handleParams(params, officeRuntime);
        runBody(unit, list, officeRuntime);
    }

    public void runBody(OfficeUnit unit, List<Object> params, OfficeRuntime officeRuntime){
        templateProc.run(unit, params, officeRuntime);
    }

    public TemplateProc getTemplateProc() {
        return templateProc;
    }

    public void setTemplateProc(TemplateProc templateProc) {
        this.templateProc = templateProc;
    }

    public TypeItem getType() {
        return templateProc.getType();
    }

    protected List<Object> handleParams(List<Object> params, OfficeRuntime officeRuntime){
        List<Object> result = new ArrayList<Object>();
        for (Object param : params) {
            result.add(handleParam(param, officeRuntime));
        }
        return result;
    }

    private Object handleParam(Object param, OfficeRuntime officeRuntime){
        if (param instanceof FuncBase) {
            FuncBase funcNode = (FuncBase) param;
            Object result = funcNode.run(officeRuntime);
            return result;
        }else {
            return param;
        }
    }

    public List<Object> getParams() {
        return params;
    }

    public void addParam(Object param) {
        this.params.add(param);
    }

    public void addParams(List<Object> params){
        for (Object param : params) {
            addParam(param);
        }
    }
}
